package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2020-11-24 10:42
 *
 * https://leetcode-cn.com/problems/sort-colors/
 */
public class _75_颜色分类 {

    public void sortColors(int[] nums) {

        if (nums == null || nums.length <= 1) {

            return;
        }

        int left = 0, index = 0, right = nums.length - 1;



        while (index <= right) {

            while (left < nums.length && nums[left] == 0) {
                left++;
            }

            if (left == nums.length) {

                return;
            }
            index = left;

            while (index <= right && nums[index] == 1) {
                index++;
            }

            if (index > right ) {

                break;
            }

            if (nums[index] == 0) {

                swap(nums,left,index);
                left++;
            }else {

                while (index <= right && nums[right] == 2) {

                    right--;
                }

                if (index > right) {

                    break;
                }

                swap(nums,index,right);
                right--;
            }
        }

    }

    private void swap(int[] nums, int i1, int i2){

        int tmp = nums[i1];
        nums[i1] = nums[i2];
        nums[i2]  = tmp;
    }
}
